package com.sdksoft.readcard.utils

import com.sdksoft.readcard.service.UserService
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit
import com.sdksoft.readcard.utils.convertadapter.GsonConverterFactory
/**
 * @author mtj
 * @date 2023-4-14
 * @desc
 * @email mtjsoft3@gmail.com
 */
class NetworkManager {

    val dataBaseUrl = "https://epassport.sfzydq.com/"
//    val dataBaseUrl = "http://192.168.1.248:18080/" // 数据服务地址

    companion object {
        val init: NetworkManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            NetworkManager()
        }
    }

    private fun logInterceptor(): MyHttpLoggingInterceptor {
        val httpLoggingInterceptor = MyHttpLoggingInterceptor()
        httpLoggingInterceptor.level = MyHttpLoggingInterceptor.Level.BODY
        return httpLoggingInterceptor
    }

    private fun defaultHttpClient(interceptor: MyHttpLoggingInterceptor): OkHttpClient {
        val clientBuilder = OkHttpClient.Builder()
        clientBuilder.apply {
            addNetworkInterceptor(interceptor)
            connectTimeout(15000, TimeUnit.MILLISECONDS)
            writeTimeout(15000, TimeUnit.MILLISECONDS)
            readTimeout(15000, TimeUnit.MILLISECONDS)
            retryOnConnectionFailure(false)
            dns(DnsTimeOut(5000, TimeUnit.MILLISECONDS))
        }
        return clientBuilder.build()
    }

    private fun defaultRetrofit(client: OkHttpClient): Retrofit {
        val builder = Retrofit.Builder()
            .client(client)
            .baseUrl(dataBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
        return builder.build()
    }

    /**
     * 接口
     */
    fun userService(): UserService {
        return defaultRetrofit(defaultHttpClient(logInterceptor())).create(
            UserService::class.java
        )
    }

}

